<?php

namespace Frieza\Modules\AdServing\Actions;

use Doraemon\model\AdServing\Serving;
use Doraemon\tools\Log;
use Encore\Admin\Actions\BatchAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BatchUpdateAdmin extends BatchAction
{
    public $name = '修改负责人';

    private const ROLE_NAME = '增长投放';

    public function handle($idStr, Request $request)
    {
        $admin_uid = $request->get('admin_uid');

        $role = DB::table('frieza.admin_roles')
            ->where('name', self::ROLE_NAME)
            ->first();
        $exist = DB::table('frieza.admin_role_users')
            ->where('user_id',  Admin::user()->id)
            ->where('role_id', $role->id)
            ->first();
        if (empty($exist)) {
            Log::error('非投放组的用户修改投放负责人', [$roleId, Admin::user()]);
            return $this->response()->error('您所属的角色无法修改');
        }

        $idArr = explode(',', $idStr);
        Log::debug('修改负责人', [$admin_uid, $idArr]);

        Serving::update([
            'admin_uid' => $admin_uid,
        ], [
            'id' => $idArr,
        ]);
        return $this->response()->success('修改成功')->refresh();
    }

    public function form()
    {
        $roleName = self::ROLE_NAME;
        $rows = DB::select(<<<SQL
select A.id,A.name from frieza.`admin_users` A
join frieza.`admin_role_users` B on A.id=B.user_id
join frieza.`admin_roles` C on B.role_id=C.id and C.`name`='{$roleName}'
SQL
);
        $options = [];
        foreach ($rows as $row) {
            $options[$row->id] = $row->name;
        }

        $this->select('admin_uid', '负责人')->options($options)->rules('required');
    }

//    public function dialog()
//    {
//        $this->confirm('确定修改负责人？');
//    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }
        return $key;
    }

}
